// js/data/ResourceManager.js
import imageAssets from '../data/imageAssets.js';

export default class ResourceManager {
  constructor() {
    this.images = new Map();
    this.sounds = new Map();
    this.totalResources = 0;
    this.loadedResources = 0;
    this.progressCallback = null;

    // 页面资源映射
    this.pageResourceMap = new Map();
    this.initPageResourceMap();
  }

  // 设置进度回调
  setProgressCallback(callback) {
    this.progressCallback = callback;
  }

  // 初始化页面资源映射
  initPageResourceMap() {
    // 定义每个页面需要的资源
    this.pageResourceMap.set('login', ['loadingLog', 'loadingBtn']);
    this.pageResourceMap.set('home', ['mainBg', 'practiceBtn', 'rankingBtn', 'challengeBtn', 'defaultAvatar', 'shareIcon']);
    this.pageResourceMap.set('profile', ['userBg', 'backIcon', 'userLogs', 'shareBg', 'shareBottomIcon']);
    this.pageResourceMap.set('leaderboard', ['rankingBg', 'rankingIcon', 'rankingIconSelect', 'challengeIcon', 'challengeIconSelect']);
    this.pageResourceMap.set('game', ['buyIcon', 'sellIcon', 'startIcon', 'gamePop', 'changeDiceIcon', 'gameResultPop']);
    this.pageResourceMap.set('settlement', ['tipsIcon', 'earnIcon', 'recordBg', 'showIcon', 'againIcon', 'promptCard']);
    this.pageResourceMap.set('sign', ['signPopupBg', 'claimedIcon', 'showRewardBtn', 'dayIcon1', 'dayIcon2', 'dayIcon3', 'dayIcon4', 'dayIcon5', 'dayIcon6', 'dayIcon7']);
  }

  // 带重试机制的图片加载
  loadImageWithRetry(key, src, retries = 3) {
    return new Promise((resolve, reject) => {
      // 如果已经加载过，直接返回
      if (this.images.has(key)) {
        resolve();
        return;
      }

      const attemptLoad = (attempt) => {
        const image = wx.createImage();
        image.onload = () => {
          this.images.set(key, image);
          this.loadedResources++;
          this.updateProgress();
          resolve();
        };
        image.onerror = () => {
          console.warn(`[ResourceManager] Failed to load ${src} (attempt ${attempt})`);
          if (attempt < retries) {
            setTimeout(() => attemptLoad(attempt + 1), 500 * attempt);
          } else {
            console.error(`[ResourceManager] Failed to load image after ${retries} attempts: ${src}`);
            this.loadedResources++;
            this.updateProgress();
            resolve(); // 继续执行，避免阻塞
          }
        };
        image.src = src;
      };
      attemptLoad(1);
    });
  }

  // 【核心优化】分批次加载资源
  async loadAllResources() {
    const allResources = imageAssets.imageAssetsList;

    // 定义资源批次和优先级
    const resourceBatches = {
      critical: ['loadingLog', 'loadingBtn'], // 关键资源：登录页面
      high: ['mainBg', 'practiceBtn', 'rankingBtn', 'challengeBtn', 'defaultAvatar', 'shareIcon'], // 高优先级：主页
      normal: ['userBg', 'backIcon', 'userLogs', 'rankingBg', 'rankingIcon', 'rankingIconSelect', 'challengeIcon', 'challengeIconSelect', 'shareBg', 'shareBottomIcon'], // 普通优先级：个人信息和排行榜
      low: [] // 低优先级：其他资源
    };

    // 将剩余资源归类到低优先级
    const criticalHighNormal = [...resourceBatches.critical, ...resourceBatches.high, ...resourceBatches.normal];
    allResources.forEach(resource => {
      if (!criticalHighNormal.includes(resource.name)) {
        resourceBatches.low.push(resource.name);
      }
    });

    // 将资源名称映射到完整的资源对象
    const resourceMap = new Map(allResources.map(item => [item.name, item]));

    // 为每个批次创建完整的资源对象数组
    const batches = {};
    Object.keys(resourceBatches).forEach(priority => {
      batches[priority] = resourceBatches[priority].map(name => {
        const resource = resourceMap.get(name);
        if (!resource) {
          console.warn(`[ResourceManager] Resource "${name}" not found in imageAssets.js`);
        }
        return resource;
      }).filter(Boolean);
    });

    // 计算总资源数
    this.totalResources = allResources.length;
    this.loadedResources = 0;

    // 按批次加载
    console.log('[ResourceManager] Starting batch loading...');

    // 首先加载关键资源
    await this.loadBatch(batches.critical, 'critical');
    console.log('[ResourceManager] Critical resources loaded.');

    // 然后加载高优先级资源
    await this.loadBatch(batches.high, 'high');
    console.log('[ResourceManager] High priority resources loaded.');

    // 在后台加载普通和低优先级资源
    this.loadBatch(batches.normal, 'normal').then(() => {
      console.log('[ResourceManager] Normal priority resources loaded.');
    });
    this.loadBatch(batches.low, 'low').then(() => {
      console.log('[ResourceManager] Low priority resources loaded.');
    });
  }

  // 【新增】预加载页面资源
  async preloadPageResources(pageName) {
    const requiredResources = this.pageResourceMap.get(pageName);
    if (!requiredResources || requiredResources.length === 0) {
      return;
    }

    console.log(`[ResourceManager] Preloading resources for page: ${pageName}`);

    // 获取所有资源配置
    const allResources = imageAssets.imageAssetsList;
    const resourceMap = new Map(allResources.map(item => [item.name, item]));

    // 过滤出需要加载且未加载的资源
    const resourcesToLoad = requiredResources
      .map(name => resourceMap.get(name))
      .filter(resource => resource && !this.images.has(resource.name));

    if (resourcesToLoad.length === 0) {
      console.log(`[ResourceManager] All resources for page "${pageName}" are already loaded.`);
      return;
    }

    // 并行加载页面资源
    const promises = resourcesToLoad.map(resource =>
      this.loadImageWithRetry(resource.name, resource.src)
    );

    try {
      await Promise.all(promises);
      console.log(`[ResourceManager] Successfully preloaded ${resourcesToLoad.length} resources for page "${pageName}".`);
    } catch (error) {
      console.error(`[ResourceManager] Error preloading resources for page "${pageName}":`, error);
    }
  }

  // 加载一个批次的资源
  async loadBatch(batch, batchName) {
    if (!batch || batch.length === 0) {
      console.log(`[ResourceManager] Batch "${batchName}" is empty, skipping.`);
      return;
    }

    const promises = batch.map(resource => {
      return this.loadImageWithRetry(resource.name, resource.src);
    });
    await Promise.all(promises);
  }

  // 更新加载进度
  updateProgress() {
    if (this.progressCallback) {
      const progress = (this.loadedResources / this.totalResources) * 100;
      this.progressCallback(progress);
    }
  }

  // 获取图片（增强版）
  getImage(key) {
    const image = this.images.get(key);
    if (!image) {
      console.warn(`[ResourceManager] Image with key "${key}" not found or not yet loaded.`);
      // 返回一个占位符对象，避免 drawImage 报错
      return this.createPlaceholderImage();
    }
    return image;
  }

  // 【新增】创建占位符图片
  createPlaceholderImage() {
    const canvas = wx.createCanvas(100, 100);
    const ctx = canvas.getContext('2d');

    // 绘制简单的占位符
    ctx.fillStyle = '#333333';
    ctx.fillRect(0, 0, 100, 100);
    ctx.fillStyle = '#ffffff';
    ctx.font = '12px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('Loading...', 50, 50);

    return canvas;
  }

  // 检查图片是否已加载
  isImageLoaded(key) {
    return this.images.has(key);
  }

  // 获取声音
  getSound(key) {
    return this.sounds.get(key);
  }
}



